package com.my.hotel.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.my.hotel.entity.*;
import com.my.hotel.service.*;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.RequestPartServletServerHttpRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/user",produces = "text/html;charset=utf-8")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private ExcelService excelService;

    @Autowired
    private OrderService orderService;

    //主页跳转
    @RequestMapping("/jump")
    public String jump(Model model, HttpSession session){
        //查询用户所有用的菜单权限
        User user =(User) session.getAttribute("userinfo");
        List<Menu> menuList = menuService.getMenuList(user.getId());
        model.addAttribute("menuList",menuList);
        return "home";
    }
    //分页查询
    @RequestMapping("/userPage")
    public String getPage(Model model,Integer pageNo,String status){
        //回显复选框
        model.addAttribute("status",status);
        if(pageNo==null){
            pageNo=1;
        }
        PageHelper.startPage(pageNo,10);
        // 判断状态是否为空字符串
        if ("".equals(status)){
            status=null;
        }
        List<User> list = userService.getList(status);

        PageInfo<User> page = new PageInfo<User>(list);
        model.addAttribute("page",page);
        return "userPage";
    }
    //用户预添加
    @RequestMapping("/addPreUser")
    public String addPreUser(){
        return "userAdd";
    }
    //用户添加
    @RequestMapping("/addUser")
    public String addUser(User user,Model model){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setCreateTime(sdf.format(date));
        user.setOpratorId(1);
        String encode = new BCryptPasswordEncoder().encode(user.getPassword());
        user.setPassword(encode);
        userService.addUser(user);
        return getPage(model);
    }
    //用户删除
    @RequestMapping("/delUser")
    public String delUser(int id,Model model){
        userService.delUser(id);
        return getPage(model);
    }
    //用户预修改
    @RequestMapping("/updPreUser")
    public String updatePreUser(int id,Model model){
        User user = userService.getUserById(id);
        model.addAttribute("user",user);
        return "userUpdate";
    }
    //用户修改
    @RequestMapping("/updUser")
    public String updateUser(User user,Model model){
        String encode = new BCryptPasswordEncoder().encode(user.getPassword());
        user.setPassword(encode);
        userService.updateUser(user);
        return getPage(model);
    }
    //跳转到分配页面
    @RequestMapping("/toDistRole")
    public String toDistRole(int userId,Model model){
        //查询已分配的角色
        List<Role> distRole = roleService.getDistRole(userId);
        //查询未分配的角色
        List<Role> unDistRole = roleService.getUnDistRole(userId);
        model.addAttribute("distRole",distRole);
        model.addAttribute("unDistRole",unDistRole);
        model.addAttribute("userId",userId);
        return "distRole";
    }

    //添加用户关联的角色
    @RequestMapping("/addUserRole")
    public String addUserRole(int userId,int[] roleId){
        ArrayList<UserRole> list = new ArrayList<UserRole>();
        for (int rid : roleId) {
            UserRole ur = new UserRole();
            ur.setRoleId(rid);
            ur.setUserId(userId);
            list.add(ur);
        }
        userService.addUserRole(list);
        return "success";
    }
    //用户导出
    @RequestMapping("/exportUser")
    public String exportUser(HttpServletResponse response, HttpServletRequest request) throws IOException {
        //把用户数据查询出来
        List<User> list = userService.getList(null);
        //把数据全部写入到excel对象中 然后把excel的对象通过流的方式写入到本地
        //导入poi的jar
        //获取流对象
        ServletOutputStream os = response.getOutputStream();
        //设置excel文件格式
        response.setContentType("application/vnd.ms-excel");
        //设置打开方式 attachment：附件下载   filename=report.xlsx 文件名为report.xlsx
        response.setHeader("content-Disposition","attachment;filename=exportUser.xlsx");
        //创建excel对象
        XSSFWorkbook sheets = new XSSFWorkbook();
        //创建工作表对象
        XSSFSheet sheet = sheets.createSheet("酒店信息管理系统用户数据列表");
        //添加表头信息 获取表格第一行
        XSSFRow row_title = sheet.createRow(0);
        List<ExcelDTO> lisetExcel = excelService.getList("tb_user");
        for (int i = 0; i < lisetExcel.size(); i++) {
            ExcelDTO excelDTO = lisetExcel.get(i);
            if(excelDTO.getColumnName().equals("oprator_id")){
                continue;
            }
            if(excelDTO.getColumnName().equals("id")){
                row_title.createCell(i).setCellValue("序号");
            }else{
                row_title.createCell(i).setCellValue(excelDTO.getColumnComment());
            }

        }
        /*//创建第一个单元格
        row_title.createCell(0).setCellValue("序号");
        row_title.createCell(1).setCellValue("用户名");
        row_title.createCell(2).setCellValue("昵称");
        row_title.createCell(3).setCellValue("真实姓名");
        row_title.createCell(4).setCellValue("性别");
        row_title.createCell(5).setCellValue("邮箱地址");
        row_title.createCell(6).setCellValue("电话号码");
        row_title.createCell(7).setCellValue("身份证号");
        row_title.createCell(8).setCellValue("状态");
        row_title.createCell(9).setCellValue("创建时间");*/

        for (int i = 0; i < list.size(); i++) {
            User user = list.get(i);
            XSSFRow row = sheet.createRow(i + 1);
//            XSSFCell cell = row.createCell(0);
//            XSSFCellStyle style = new XSSFCellStyle(null);
//            XSSFFont xssfFont = new XSSFFont(null);
//            xssfFont.setColor((short)100);
//            style.setFont(xssfFont);
//            cell.setCellStyle(style);
            row.createCell(0).setCellValue(i+1);
            row.createCell(1).setCellValue(user.getUsername());
            row.createCell(2).setCellValue(user.getPassword());
            row.createCell(3).setCellValue(user.getNickname());
            row.createCell(4).setCellValue(user.getRealname());
            if("0".equals(user.getGender())){
                row.createCell(5).setCellValue("女");
            }else if("1".equals(user.getGender())){
                row.createCell(5).setCellValue("男");
            }else{
                row.createCell(5).setCellValue("未知");
            }
            row.createCell(6).setCellValue(user.getImageUrl());
            row.createCell(7).setCellValue(user.getEmail());
            row.createCell(8).setCellValue(user.getPhone());
            row.createCell(9).setCellValue(user.getIdCard());
            if("0".equals(user.getStatus())){
                row.createCell(10).setCellValue("删除");
            }else if("1".equals(user.getStatus())){
                row.createCell(10).setCellValue("启用");
            }else if("2".equals(user.getStatus())){
                row.createCell(10).setCellValue("禁用");
            }
            row.createCell(11).setCellValue(user.getCreateTime());
//            row.createCell(12).setCellValue(user.getOpratorId());
        }

        //通过流把数据写出到本地文件
        sheets.write(os);
        //刷新
        os.flush();
        //释放资源
        os.close();
        sheets.close();
        return null;
    }

    //用户导入
    @RequestMapping("/importUser")
    @ResponseBody
    public String importUser(MultipartFile file) throws IOException {
        //创建集合
        List<User> list = new ArrayList<User>();
        //获取输入流
        InputStream is = file.getInputStream();
        //创建excel文档对象
        XSSFWorkbook sheets = new XSSFWorkbook(is);
        //获取工作表对象
        XSSFSheet sheetAt = sheets.getSheetAt(0);
        //获取头行和尾行
        int firstRowNum = sheetAt.getFirstRowNum();
        int lastRowNum = sheetAt.getLastRowNum();
        for (int i = firstRowNum+1; i <=lastRowNum ; i++) {
            //根据索引获取当前行对象
            XSSFRow row = sheetAt.getRow(i);
            User user = new User();
            String username = row.getCell(1).getStringCellValue();
            user.setUsername(username);
            String password = row.getCell(2).getStringCellValue();
            user.setPassword(password);
            String nickname = row.getCell(3).getStringCellValue();
            user.setNickname(nickname);
            String realname = row.getCell(4).getStringCellValue();
            user.setRealname(realname);
            String gender = row.getCell(5).getStringCellValue();
            if("男".equals(gender)){
                user.setGender("1");
            }else if("女".equals(gender)){
                user.setGender("0");
            }
            String email = row.getCell(7).getStringCellValue();
            user.setEmail(email);
            String phone = row.getCell(8).getStringCellValue();
            user.setPhone(phone);
            String idCard = row.getCell(9).getStringCellValue();
            user.setIdCard(idCard);
            String status = row.getCell(10).getStringCellValue();
            if("启用".equals(status)){
                user.setStatus("1");
            }else if("禁用".equals(status)){
                user.setStatus("2");
            }else if("删除".equals(status)){
                user.setStatus("0");
            }
            String createTime = row.getCell(11).getStringCellValue();
            user.setCreateTime(createTime);
            list.add(user);
//            short firstCellNum = row.getFirstCellNum();
//            short lastCellNum = row.getLastCellNum();
//            for (int j = firstCellNum+1; j < lastCellNum; j++) {
//                XSSFCell cell = row.getCell(j);
//                String value = cell.getStringCellValue();
//                System.out.println(value);
//            }
            /*//获取单元格对象
            XSSFCell cell = row.getCell(0);
            //获取当前单元格的值
            double numericCellValue = cell.getNumericCellValue();
            System.out.println(numericCellValue);*/
        }
        //批量保存数据
        userService.addBatchUser(list);
        return "success";
    }

    // 跳转修改
    @RequestMapping("/jump1")
    public String jump1(){
        return "peasonUpdate";
    }

    @RequestMapping("/jump3")
    public String jump3(){
        return "updUserPass";
    }

    @RequestMapping("/jump2")
    public String jump2(String pageNow,String pageNow1,String pageNow2,String pageNow3,String pageNow4,String pageNow5,String orderStatus,HttpSession session,Model model){
        User userinfo =(User) session.getAttribute("userinfo");
        int userId = userinfo.getId();
//        System.out.println(pageNow);
        if(pageNow==null){
            pageNow="1";
        }
        if(pageNow1==null){
            pageNow1="1";
        }
        if(pageNow2==null){
            pageNow2="1";
        }
        if(pageNow3==null){
            pageNow3="1";
        }
        if(pageNow4==null){
            pageNow4="1";
        }
        if(pageNow5==null){
            pageNow5="1";
        }
        //  查询全部
        PageHelper.startPage(Integer.parseInt(pageNow),3);
        List<OrderDTO> orderList = orderService.getOrderList(userId,orderStatus,null);
        PageInfo<OrderDTO> pageInfo = new PageInfo<OrderDTO>(orderList);
        model.addAttribute("pageInfo",pageInfo);

        // 查询 已完成订单
        PageHelper.startPage(Integer.parseInt(pageNow1),3);
        List<OrderDTO> orderList1 = orderService.getOrderList(userId,"3",null);
        PageInfo<OrderDTO> pageInfo1 = new PageInfo<OrderDTO>(orderList1);
        model.addAttribute("pageInfo1",pageInfo1);

        // 查询 入住订单
        PageHelper.startPage(Integer.parseInt(pageNow2),3);
        List<OrderDTO> orderList2 = orderService.getOrderList(userId,"2",null);
        PageInfo<OrderDTO> pageInfo2 = new PageInfo<OrderDTO>(orderList2);
        model.addAttribute("pageInfo2",pageInfo2);

        // 查询 已取消订单
        PageHelper.startPage(Integer.parseInt(pageNow3),3);
        List<OrderDTO> orderList3 = orderService.getOrderList(userId,"1",null);
        PageInfo<OrderDTO> pageInfo3 = new PageInfo<OrderDTO>(orderList3);
        model.addAttribute("pageInfo3",pageInfo3);

        // 查询 预定订单
        PageHelper.startPage(Integer.parseInt(pageNow4),3);
        List<OrderDTO> orderList4 = orderService.getOrderList(userId,"0",null);
        PageInfo<OrderDTO> pageInfo4 = new PageInfo<OrderDTO>(orderList4);
        model.addAttribute("pageInfo4",pageInfo4);

        // 查询 未点评订单
        PageHelper.startPage(Integer.parseInt(pageNow5),3);
        List<OrderDTO> orderList5 = orderService.getOrderList(userId,"3","0");
        PageInfo<OrderDTO> pageInfo5 = new PageInfo<OrderDTO>(orderList5);
        model.addAttribute("pageInfo5",pageInfo5);

        return "wodedingdan";
    }

//    @RequestMapping("/jump4")
//    @ResponseBody
//    public String jump4(String pageNow,String orderStatus,HttpSession session,Model model){
//        User userinfo =(User) session.getAttribute("userinfo");
//        int userId = userinfo.getId();
////        System.out.println(pageNow);
//        if(pageNow==null){
//            pageNow="1";
//        }
//        PageHelper.startPage(Integer.parseInt(pageNow),3);
//        List<OrderDTO> orderList = orderService.getOrderList(userId,orderStatus);
//        //PageInfo<OrderDTO> pageInfo = new PageInfo<OrderDTO>(orderList);
//        // model.addAttribute("pageInfo",pageInfo);
//        String s = JSON.toJSONString(orderList);
////        req.getRequestDispatcher("")
//        return s;
//    }

    // 修改个人信息
    @RequestMapping("/updPeason")
    public String updPeason(User user,HttpSession session){
        userService.updPeason(user);
        User user1 = userService.getUserById(user.getId());
        session.setAttribute("userinfo",user1);
//        System.out.println(user1);
        return "success";
    }

    // 修改密码
    @RequestMapping("/updUserPass")
    public String updUserPass(Pass pass, HttpSession session, Model model){
        if(pass.getNewPassword().equals(pass.getConfirmPassword())){
            String encode1 = new BCryptPasswordEncoder().encode(pass.getNewPassword());
            userService.updUserPass(pass.getUserId(),encode1);
        }
        return "success";
    }

    //重载一下
    public String getPage(Model model){
        return getPage(model,1,null);
    }
}
